define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, Promotionsdetail, $stateParams, $window, $timeout, $ionicSlideBoxDelegate, GoPage, GoDialog, $ionicModal,
		$ionicPopup, Auth, ChatInfo, GoPicture, $ionicPlatform, GoChat, $ionicScrollDelegate) {
			
		$scope.showClass = "ion-ios-plus-outline";
		//画面加载
		$scope.$on('$ionicView.afterEnter', function() {
			$scope.init_data();
		}, false);
		
		//直播获取
		$scope.livedata = function() {
			//获取token
			var params = new Object();
			params.as_id = $scope.as_id;
			params.act_id = $scope.act_id;
			params.nPage = 1;
			Promotionsdetail.get_live_data(params, function(data) {
				console.log(data)
				if(!data.success){
					GoDialog.alert("提示",data.msg,function(){
						GoPage.go_back();
					});
					return;
				}
				if(!data.result||!data.result.groups){
					GoDialog.alert("提示","暂时没有群哦！",function(){
						GoPage.go_back();
					});
					return;
				}
				$scope.group = data.result.groups;
				$scope.group_id = $scope.group[0].group_id;
				$scope.group_code = $scope.group[0].group_code;
				$scope.introduce = data.result.description;
				$scope.group_goods = data.result.goods;
				$scope.act_name = data.result.act_name;
				if($scope.group.length > 1) {
					$scope.other_group_id = $scope.group[1].group_id;
					$scope.other_group_code = $scope.group[1].group_code;
				} else {
					$scope.other_group_id = '';
					$scope.other_group_code = '';
				}
				$scope.init_chat();
			})
		};
		
		/**********************************聊天群******************************/
		$scope.$on('$ionicView.afterLeave', function() {
			GoChat.closeConnect();
		}, false);
		$ionicPlatform.on('resume', function() {
			GoChat.openConnect($scope.socket_url, $scope.user_id, $scope.login_code);
			$scope.get_msg();
		})
		$scope.update_position = function() {
			$scope.nowHeight = document.getElementById("cdef").clientHeight;
			if($scope.height == 0)
				$scope.height = $scope.nowHeight;
			$scope.delegate.scrollBy(0, $scope.nowHeight - $scope.height, [false]);
		}
		/*
		 * 处理群信息
		 */
		$scope.get_groupinfo = function() {
			$scope.is_show = true;
			$scope.is_admin = false;
			$scope.login_code = ChatInfo.get_chatLoginCode();
			$scope.chat_url = ChatInfo.get_chatUrl();
			$scope.socket_url = ChatInfo.get_chatSoketUrl();
			$scope.member_id = Auth.get_memberId();
			Promotionsdetail.get_groupinfo($scope.group_id, function(data) {
				$scope.whitle_list = new Array();
				$scope.black_list = new Array();
				$scope.members = new Array();
				$scope.advance = data.advance;//账号余额
				for(var i = 0; i < data.members.length; i++) {
					$scope.members[data.members[i].user_id] = data.members[i];
					//处理黑白名单
					if(data.members[i].is_black == 'false') {
						var n = $scope.whitle_list.length;
						$scope.whitle_list[n] = data.members[i];
					} else {
						var n = $scope.black_list.length;
						$scope.black_list[n] = data.members[i];
					}
					//处理头像数据
					$scope.member_logo[data.members[i].user_id] = {
						"image_logo": data.members[i].image_logo,
						"nickname": data.members[i].nickname
					}

					//处理当前用户member_id
					if($scope.member_id == data.members[i].member_id) {
						$scope.user_id = data.members[i].user_id;
						$scope.is_admin = data.members[i].is_main;
						$scope.is_black = data.members[i].is_black;
						$scope.user_name = data.members[i].nickname;
						if($scope.is_admin == 'false')
							$scope.is_admin = false;
						else
							$scope.is_admin = true;
						if($scope.is_black == 'false')
							$scope.is_black = false;
						else
							$scope.is_black = true;
					}
				}
				if($scope.is_admin == true) {
					$scope.list = data.members;
				} else {
					$scope.list = $scope.whitle_list;
				}
				$scope.data = data;
				$scope.group_code = data.group.group_code;
				if(parseInt(data.group.max_gnum) > parseInt(data.redlimit.number)) {
					$scope.max_redNum = parseInt(data.redlimit.number);
				} else
					$scope.max_redNum = parseInt(data.group.max_gnum);
			}, function() {
				//开启长链接
				GoChat.openConnect($scope.socket_url, $scope.user_id, $scope.login_code);
				$scope.get_msg();
			});

		};
		$scope.get_msg = function() {
			GoChat.getChatMsg(function() {
				$scope.get_message();
			}, $scope)
		}
		/*
		 * 初始化消息获取lsatMsgId
		 */
		$scope.get_message = function() {
			//小小图加密
			var accessType = 'get';
			var path = '/message/getChatMsg';
			var param = new Array();
			param['loginCode'] = $scope.login_code;
			param['lastMsgId'] = $scope.msg_id;
			window.Secret.SetNonceAndTime();
			siginfo.sig = $scope.encode(accessType, path, param);
			Promotionsdetail.get_message(siginfo, $scope.login_code, $scope.chat_url, $scope.msg_id, function(data) {
				data = JSON.parse(data)
				var msg = new Object();
				msg['chartList'] = new Array();
				var other_msg = new Object();
				other_msg['chartList'] = new Array();
				if(data.chartList) {
					//这里要区分收到的消息
					for(var i = 0; i < data.chartList.length; i++) {
						if(data.chartList[i].groupId == $scope.group_code) {
							var j = msg.length;
							msg['chartList'].push(data.chartList[i]);
						} else if(data.chartList[i].groupId == $scope.other_group_code) {
							var n = other_msg.length;
							other_msg['chartList'].push(data.chartList[i]);
						}
					}
					if(msg['chartList'].length > 0)
						$scope.handle_message(msg, false, false);
					else if(other_msg['chartList'].length > 0)
						$scope.handle_message(other_msg, false, true);
				}
				if(data.lastMsgId)
					$scope.msg_id = data.lastMsgId;
			})
		};
		/*
		 * 获取历史消息
		 */
		$scope.get_history = function() {
			//小小图加密
			var accessType = 'get';
			var path = '/message/getChatMsgHistoryByDate';
			var param = new Array();
			param['loginCode'] = $scope.login_code;
			param['lastMsgId'] = $scope.histroyMsg_id;
			siginfo.sig = $scope.encode(accessType, path, param);
			Promotionsdetail.get_histroy(siginfo, $scope.login_code, $scope.chat_url, $scope.histroyMsg_id, $scope.group_code, function(data) {
				data = JSON.parse(data);
				//				console.log(data.lastMsgId);
				$scope.histroyMsg_id = data.msgId;
				$scope.handle_message(data, true, false);
				//				console.log(data);
			}, function() {
				$scope.$broadcast('scroll.refreshComplete');
				$timeout(function() {
					$scope.isLoad = false;
				}, 1000);
			})
		};
		/*
		 * 处理历史消息
		 */
		$scope.handle_message = function(data, is_history, is_other) {
			if(data.chartList != undefined) {
				for(var j=0;j<data.chartList.length;j++){
					data.chartList[j].nickName = $scope.members[data.chartList[j].memberId].nickname;
				}
				var message_data = new Array();
				//将获取到的历史消息倒转
				if(is_history == true)
					message_data = data.chartList.reverse();
				else
					message_data = data.chartList;
				for(var i = 0; i < message_data.length; i++) {
					var chatTime = message_data[i].sendTime;
					var sendDateTime = chatTime.substr(0, 4) + '-' + chatTime.substr(4, 2) + '-' + chatTime.substr(6, 2) + ' ';
					sendDateTime += chatTime.substr(8, 2) + ':' + chatTime.substr(10, 2) + ':' + chatTime.substr(12, 2);
					message_data[i].sendTime = sendDateTime;
					message_data[i].content = decodeURIComponent(message_data[i].content);
					//				 history_data[i].nickName = decodeURIComponent(history_data[i].nickName);
					if(message_data[i].content.indexOf("hongbao") >= 0) {
						var hongbao = new Array();
						//0：标志位, 1:留言,2:会员id ,3:昵称,4:红包id,5:红包类型
						message_data[i].hongbao = message_data[i].content.split(':');
					} else {
						message_data[i].content = emojione.toImage(message_data[i].content);

					}
					if(message_data[i].type == 'P') {
						$scope.get_img(message_data, i, message_data[i].memberId, message_data[i].file);
					}
				}
				if(is_other != true) {
					//合并消息
					if(is_history == true) {
						if($scope.is_firstHistroy == true) {
							$scope.show_message.splice(0, $scope.show_message.length);
							$scope.is_firstHistroy = false;
						}
						$scope.show_message = message_data.concat($scope.show_message);
					} else
						$scope.show_message = $scope.show_message.concat(message_data);
					//				console.log(is_history);
					if(is_history == true) {
						//更新之前聊天消息位置
						$timeout(function() {
							$scope.update_position();
						}, 10);
					} else {
						$timeout(function() {
							$scope.delegate.scrollBottom(true);
						}, 10);
					}
				} else {
					if(is_history == true) {
						if($scope.is_otherFirstHistroy == true) {
							$scope.other_message.splice(0, $scope.show_message.length);
							$scope.is_otherFirstHistroy = false;
						}
						$scope.other_message = message_data.concat($scope.other_message);
					} else
						$scope.other_message = $scope.other_message.concat(message_data);
				}

			}
		};
		/*
		 * 小小图加密
		 */
		$scope.encode = function(accessType, path, param) {
			var accessType = accessType;
			var path = path;
			var param = param;
			window.Secret.SetNonceAndTime();
			return encodeURIComponent(window.Secret.GetSig(accessType, path, param));
		};
		$scope.get_img = function(data, index, frUserId, fileName) {
			var histroy_data = new Array();
			histroy_data = data;
			var accessType = 'get';
			var path = '/message/getPhoto';
			var param = new Array();
			param['loginCode'] = $scope.login_code;
			param['frUserId'] = frUserId;
			param['fileName'] = fileName;
			siginfo.sig = $scope.encode(accessType, path, param);
			histroy_data[index].url = Promotionsdetail.get_img($scope.chat_url, param, siginfo);
		};
		$scope.openMore = function() {
			if($scope.biaoClass == "tohide" || $scope.biaoClass == ""){
				$scope.biaoClass = "toshow";
				$scope.showClass = "ion-ios-minus-outline";
			}
			else{
				$scope.biaoClass = "tohide";
				$scope.showClass = "ion-ios-plus-outline";
			}
		};
		/**
		 * 初始化emoji表情相关
		 */
		$scope.init_emoji = function() {

			var filters = {
				smileys_people: {
					icon: "yum",
					title: "Smileys & People",
					emoji: "grinning grimacing grin joy smiley smile sweat_smile laughing innocent wink blush slight_smile " +
						"upside_down relaxed yum relieved heart_eyes kissing_heart kissing kissing_smiling_eyes " +
						"kissing_closed_eyes stuck_out_tongue_winking_eye stuck_out_tongue_closed_eyes stuck_out_tongue " +
						"money_mouth nerd sunglasses hugging smirk no_mouth neutral_face expressionless unamused rolling_eyes " +
						"thinking flushed disappointed worried angry rage pensive confused slight_frown frowning2 persevere " +
						"confounded tired_face weary triumph open_mouth scream fearful cold_sweat hushed frowning anguished " +
						"cry disappointed_relieved sleepy sweat sob dizzy_face astonished zipper_mouth mask thermometer_face " +
						"head_bandage sleeping zzz poop smiling_imp imp japanese_ogre japanese_goblin skull ghost alien robot " +
						"smiley_cat smile_cat joy_cat heart_eyes_cat smirk_cat kissing_cat scream_cat crying_cat_face " +
						"pouting_cat raised_hands clap wave thumbsup thumbsdown punch fist v ok_hand raised_hand open_hands " +
						"muscle pray point_up point_up_2 point_down point_left point_right middle_finger hand_splayed metal " +
						"vulcan writing_hand nail_care lips tongue ear nose eye eyes bust_in_silhouette busts_in_silhouette " +
						"speaking_head baby boy girl man woman person_with_blond_hair older_man older_woman man_with_gua_pi_mao " +
						"man_with_turban cop construction_worker guardsman spy santa angel princess bride_with_veil walking " +
						"runner dancer dancers couple two_men_holding_hands two_women_holding_hands bow information_desk_person " +
						"no_good ok_woman raising_hand person_with_pouting_face person_frowning haircut massage couple_with_heart " +
						"couple_ww couple_mm couplekiss kiss_ww kiss_mm family family_mwg family_mwgb family_mwbb family_mwgg " +
						"family_wwb family_wwg family_wwgb family_wwbb family_wwgg family_mmb family_mmg family_mmgb family_mmbb " +
						"family_mmgg womans_clothes shirt jeans necktie dress bikini kimono lipstick kiss footprints high_heel " +
						"sandal boot mans_shoe athletic_shoe womans_hat tophat helmet_with_cross mortar_board crown school_satchel " +
						"pouch purse handbag briefcase eyeglasses dark_sunglasses ring closed_umbrella"
				},

				animals_nature: {
					icon: "hamster",
					title: "Animals & Nature",
					emoji: "dog cat mouse hamster rabbit bear panda_face koala tiger lion_face cow pig pig_nose frog " +
						"octopus monkey_face see_no_evil hear_no_evil speak_no_evil monkey chicken penguin bird baby_chick " +
						"hatching_chick hatched_chick wolf boar horse unicorn bee bug snail beetle ant spider scorpion crab " +
						"snake turtle tropical_fish fish blowfish dolphin whale whale2 crocodile leopard tiger2 water_buffalo " +
						"ox cow2 dromedary_camel camel elephant goat ram sheep racehorse pig2 rat mouse2 rooster turkey dove " +
						"dog2 poodle cat2 rabbit2 chipmunk feet dragon dragon_face cactus christmas_tree evergreen_tree " +
						"deciduous_tree palm_tree seedling herb shamrock four_leaf_clover bamboo tanabata_tree leaves " +
						"fallen_leaf maple_leaf ear_of_rice hibiscus sunflower rose tulip blossom cherry_blossom bouquet " +
						"mushroom chestnut jack_o_lantern shell spider_web earth_americas earth_africa earth_asia full_moon " +
						"waning_gibbous_moon last_quarter_moon waning_crescent_moon new_moon waxing_crescent_moon " +
						"first_quarter_moon waxing_gibbous_moon new_moon_with_face full_moon_with_face first_quarter_moon_with_face " +
						"last_quarter_moon_with_face sun_with_face crescent_moon star star2 dizzy sparkles comet sunny " +
						"white_sun_small_cloud partly_sunny white_sun_cloud white_sun_rain_cloud cloud cloud_rain " +
						"thunder_cloud_rain cloud_lightning zap fire boom snowflake cloud_snow snowman2 snowman wind_blowing_face " +
						"dash cloud_tornado fog umbrella2 umbrella droplet sweat_drops ocean"
				},

				food_drink: {
					icon: "pizza",
					title: "Food & Drink",
					emoji: "green_apple apple pear tangerine lemon banana watermelon grapes strawberry melon cherries peach " +
						"pineapple tomato eggplant hot_pepper corn sweet_potato honey_pot bread cheese poultry_leg meat_on_bone " +
						"fried_shrimp egg hamburger fries hotdog pizza spaghetti taco burrito ramen stew fish_cake sushi bento " +
						"curry rice_ball rice rice_cracker oden dango shaved_ice ice_cream icecream cake birthday custard candy " +
						"lollipop chocolate_bar popcorn doughnut cookie beer beers wine_glass cocktail tropical_drink champagne " +
						"sake tea coffee baby_bottle fork_and_knife fork_knife_plate"
				},

				activity: {
					icon: "basketball",
					title: "Activity",
					emoji: "soccer basketball football baseball tennis volleyball rugby_football 8ball golf golfer ping_pong " +
						"badminton hockey field_hockey cricket ski skier snowboarder ice_skate bow_and_arrow fishing_pole_and_fish " +
						"rowboat swimmer surfer bath basketball_player lifter bicyclist mountain_bicyclist horse_racing levitate " +
						"trophy running_shirt_with_sash medal military_medal reminder_ribbon rosette ticket tickets performing_arts " +
						"art circus_tent microphone headphones musical_score musical_keyboard saxophone trumpet guitar violin " +
						"clapper video_game space_invader dart game_die slot_machine bowling"
				},

				travel_places: {
					icon: "rocket",
					title: "Travel & Places",
					emoji: "red_car taxi blue_car bus trolleybus race_car police_car ambulance fire_engine minibus truck " +
						"articulated_lorry tractor motorcycle bike rotating_light oncoming_police_car oncoming_bus " +
						"oncoming_automobile oncoming_taxi aerial_tramway mountain_cableway suspension_railway railway_car " +
						"train monorail bullettrain_side bullettrain_front light_rail mountain_railway steam_locomotive train2 " +
						"metro tram station helicopter airplane_small airplane airplane_departure airplane_arriving sailboat " +
						"motorboat speedboat ferry cruise_ship rocket satellite_orbital seat anchor construction fuelpump busstop " +
						"vertical_traffic_light traffic_light checkered_flag ship ferris_wheel roller_coaster carousel_horse " +
						"construction_site foggy tokyo_tower factory fountain rice_scene mountain mountain_snow mount_fuji volcano " +
						"japan camping tent park motorway railway_track sunrise sunrise_over_mountains desert beach island " +
						"city_sunset city_dusk cityscape night_with_stars bridge_at_night milky_way stars sparkler fireworks " +
						"rainbow homes european_castle japanese_castle stadium statue_of_liberty house house_with_garden " +
						"house_abandoned office department_store post_office european_post_office hospital bank hotel " +
						"convenience_store school love_hotel wedding classical_building church mosque synagogue kaaba shinto_shrine"
				},

				objects: {
					icon: "bulb",
					title: "Objects",
					emoji: "watch iphone calling computer keyboard desktop printer mouse_three_button trackball joystick " +
						"compression minidisc floppy_disk cd dvd vhs camera camera_with_flash video_camera movie_camera projector " +
						"film_frames telephone_receiver telephone pager fax tv radio microphone2 level_slider control_knobs " +
						"stopwatch timer alarm_clock clock hourglass_flowing_sand hourglass satellite battery electric_plug bulb " +
						"flashlight candle wastebasket oil money_with_wings dollar yen euro pound moneybag credit_card gem scales " +
						"wrench hammer hammer_pick tools pick nut_and_bolt gear chains gun bomb knife dagger crossed_swords shield " +
						"smoking skull_crossbones coffin urn amphora crystal_ball prayer_beads barber alembic telescope microscope " +
						"hole pill syringe thermometer label bookmark toilet shower bathtub key key2 couch sleeping_accommodation " +
						"bed door bellhop frame_photo map beach_umbrella moyai shopping_bags balloon flags ribbon gift confetti_ball " +
						"tada dolls wind_chime crossed_flags izakaya_lantern envelope envelope_with_arrow incoming_envelope e-mail " +
						"love_letter postbox mailbox_closed mailbox mailbox_with_mail mailbox_with_no_mail package postal_horn " +
						"inbox_tray outbox_tray scroll page_with_curl bookmark_tabs bar_chart chart_with_upwards_trend " +
						"chart_with_downwards_trend page_facing_up date calendar calendar_spiral card_index card_box ballot_box " +
						"file_cabinet clipboard notepad_spiral file_folder open_file_folder dividers newspaper2 newspaper notebook " +
						"closed_book green_book blue_book orange_book notebook_with_decorative_cover ledger books book link " +
						"paperclip paperclips scissors triangular_ruler straight_ruler pushpin round_pushpin triangular_flag_on_post " +
						"flag_white flag_black closed_lock_with_key lock unlock lock_with_ink_pen pen_ballpoint pen_fountain " +
						"black_nib pencil pencil2 crayon paintbrush mag mag_right"
				},

				symbols: {
					icon: "heartpulse",
					title: "Symbols",
					emoji: "heart yellow_heart green_heart blue_heart purple_heart broken_heart heart_exclamation two_hearts " +
						"revolving_hearts heartbeat heartpulse sparkling_heart cupid gift_heart heart_decoration peace cross " +
						"star_and_crescent om_symbol wheel_of_dharma star_of_david six_pointed_star menorah yin_yang orthodox_cross " +
						"place_of_worship ophiuchus aries taurus gemini cancer leo virgo libra scorpius sagittarius capricorn " +
						"aquarius pisces id atom u7a7a u5272 radioactive biohazard mobile_phone_off vibration_mode u6709 u7121 " +
						"u7533 u55b6 u6708 eight_pointed_black_star vs accept white_flower ideograph_advantage secret congratulations " +
						"u5408 u6e80 u7981 a b ab cl o2 sos no_entry name_badge no_entry_sign x o anger hotsprings no_pedestrians " +
						"do_not_litter no_bicycles non-potable_water underage no_mobile_phones exclamation grey_exclamation question " +
						"grey_question bangbang interrobang 100 low_brightness high_brightness trident fleur-de-lis part_alternation_mark " +
						"warning children_crossing beginner recycle u6307 chart sparkle eight_spoked_asterisk negative_squared_cross_mark " +
						"white_check_mark diamond_shape_with_a_dot_inside cyclone loop globe_with_meridians m atm sa passport_control " +
						"customs baggage_claim left_luggage wheelchair no_smoking wc parking potable_water mens womens baby_symbol " +
						"restroom put_litter_in_its_place cinema signal_strength koko ng ok up cool new free zero one two three four " +
						"five six seven eight nine ten 1234 arrow_forward pause_button play_pause stop_button record_button track_next " +
						"track_previous fast_forward rewind twisted_rightwards_arrows repeat repeat_one arrow_backward arrow_up_small " +
						"arrow_down_small arrow_double_up arrow_double_down arrow_right arrow_left arrow_up arrow_down arrow_upper_right " +
						"arrow_lower_right arrow_lower_left arrow_upper_left arrow_up_down left_right_arrow arrows_counterclockwise " +
						"arrow_right_hook leftwards_arrow_with_hook arrow_heading_up arrow_heading_down hash asterisk information_source " +
						"abc abcd capital_abcd symbols musical_note notes wavy_dash curly_loop heavy_check_mark arrows_clockwise " +
						"heavy_plus_sign heavy_minus_sign heavy_division_sign heavy_multiplication_x heavy_dollar_sign currency_exchange " +
						"copyright registered tm end back on top soon ballot_box_with_check radio_button white_circle black_circle " +
						"red_circle large_blue_circle small_orange_diamond small_blue_diamond large_orange_diamond large_blue_diamond " +
						"small_red_triangle black_small_square white_small_square black_large_square white_large_square small_red_triangle_down " +
						"black_medium_square white_medium_square black_medium_small_square white_medium_small_square black_square_button " +
						"white_square_button speaker sound loud_sound mute mega loudspeaker bell no_bell black_joker mahjong spades " +
						"clubs hearts diamonds flower_playing_cards thought_balloon anger_right speech_balloon clock1 clock2 clock3 " +
						"clock4 clock5 clock6 clock7 clock8 clock9 clock10 clock11 clock12 clock130 clock230 clock330 clock430 " +
						"clock530 clock630 clock730 clock830 clock930 clock1030 clock1130 clock1230 eye_in_speech_bubble"
				},

				flags: {
					icon: "flag_gb",
					title: "Flags",
					emoji: "ac af al dz ad ao ai ag ar am aw au at az bs bh bd bb by be bz bj bm bt bo ba bw br bn bg bf bi " +
						"cv kh cm ca ky cf td flag_cl cn co km cg flag_cd cr hr cu cy cz dk dj dm do ec eg sv gq er ee et fk fo " +
						"fj fi fr pf ga gm ge de gh gi gr gl gd gu gt gn gw gy ht hn hk hu is in flag_id ir iq ie il it ci jm jp " +
						"je jo kz ke ki xk kw kg la lv lb ls lr ly li lt lu mo mk mg mw my mv ml mt mh mr mu mx fm md mc mn me " +
						"ms ma mz mm na nr np nl nc nz ni ne flag_ng nu kp no om pk pw ps pa pg py pe ph pl pt pr qa ro ru rw " +
						"sh kn lc vc ws sm st flag_sa sn rs sc sl sg sk si sb so za kr es lk sd sr sz se ch sy tw tj tz th tl " +
						"tg to tt tn tr flag_tm flag_tm ug ua ae gb us vi uy uz vu va ve vn wf eh ye zm zw re ax ta io bq cx " +
						"cc gg im yt nf pn bl pm gs tk bv hm sj um ic ea cp dg as aq vg ck cw eu gf tf gp mq mp sx ss tc"
				}
			};
			for(var index in filters) {
				if(typeof(filters[index]) != "function") {
					var emoji_arr = filters[index]["emoji"].split(" ");
					var emoji_list = new Array();

					for(var i = 0; i < emoji_arr.length; i++) {
						var shortname = emoji_arr[i];

						shortname = ":" + shortname.replace(/:$/, '').replace(/^:/, '') + ":";

						var emoji_item = new Object;
						emoji_item.shortname = shortname;
						emoji_item.unicode = emojione.shortnameToUnicode(shortname);
						emoji_item.imgsrc = emojione.shortnameToImage(shortname);
						emoji_list.push(emoji_item);
					}
					$scope.emoji_map[index] = emoji_list;
				}
			}
			$ionicSlideBoxDelegate.$getByHandle('image-viewer').update(); //解决无法加载
			$ionicSlideBoxDelegate.$getByHandle('image-viewer').loop(true); //循环
			//解决输入框双向绑定问题（使用原生js方式，未找到angular的实现方式）
			/*var html_msg = document.getElementById("html_msg");
			html_msg.oninput = function() {
				html_msg.focus();
				$scope.input.message = html_msg.innerHTML;
			};*/

		};
		/**
		 * 点击表情，把表情加到输入框中
		 * @param {Object} unicode表情
		 */
		$scope.tapEmoji = function(unicode) {
			//把Unicode表情加到输入框
			$scope.input.message += unicode;
			//把Unicode表情解析成图片
			//$scope.input.message = emojione.toImage($scope.input.message);
			//console.log($scope.textFromHtml($scope.input.message));
		};
		/**
		 * 把HTML文本还原成聊天文本
		 * @param {Object} str 要过滤的字符串
		 */
		$scope.textFromHtml = function(str) {
			var invisibleChar = '&#8203;';
			str = str
				.replace(/<img[^>]*alt="([^"]+)"[^>]*>/ig, '$1')
				.replace(/\n|\r/g, '')
				.replace(/<br[^>]*>/ig, '\n')
				.replace(/(?:<(?:div|p|ol|ul|li|pre|code|object)[^>]*>)+/ig, '<div>')
				.replace(/(?:<\/(?:div|p|ol|ul|li|pre|code|object)>)+/ig, '</div>')
				.replace(/\n<div><\/div>/ig, '\n')
				.replace(/<div><\/div>\n/ig, '\n')
				.replace(/(?:<div>)+<\/div>/ig, '\n')
				.replace(/([^\n])<\/div><div>/ig, '$1\n')
				.replace(/(?:<\/div>)+/ig, '</div>')
				.replace(/([^\n])<\/div>([^\n])/ig, '$1\n$2')
				.replace(/<\/div>/ig, '')
				.replace(/([^\n])<div>/ig, '$1\n')
				.replace(/\n<div>/ig, '\n')
				.replace(/<div>\n/ig, '\n\n')
				.replace(/<(?:[^>]+)?>/g, '')
				.replace(new RegExp(invisibleChar, 'g'), '')
				.replace(/&nbsp;/g, ' ')
				.replace(/&lt;/g, '<')
				.replace(/&gt;/g, '>')
				.replace(/&quot;/g, '"')
				.replace(/&#x27;/g, "'")
				.replace(/&#x60;/g, '`')
				.replace(/&amp;/g, '&');

			return str;
		};
		//下拉获取更多
		$scope.doRefresh = function() {
			$scope.isLoad = true;
			$scope.height = document.getElementById("cdef").clientHeight;
			$scope.get_history();
		};

		var black_notice;
		$scope.show_notice = function() {
			black_notice = $ionicPopup.show({
				templateUrl: 'templates/modal/black_notice.html',
				title: "提示",
				scope: $scope, //绑定数据，必须写这行
				buttons: [{
					text: "确定",
					type: "button-assertive",
					onTap: function() { // 当点击保存按钮时，执行该函数
						Promotionsdetail.set_black($scope.group_id, user_id, is_black, function(data) {
							if(data.rtnCode == 0) {
								$scope.get_groupinfo();
								if(is_black == 1)
									GoDialog.toast('拉黑成功');
								else
									GoDialog.toast('取消拉黑成功');
							} else if(data.rtnCode == 10086) {
								GoDialog.toast(data.rtnMsg);
								GoPage.go_states("exchange_interaction");
							} else {
								GoDialog.toast(data.rtnMsg);
							}
						})
					}
				}, {
					text: "取消",
					type: "button-assertive",
					onTap: function() { // 当点击保存按钮时，执行该函数

					}
				}]
			})
		}

		$scope.update_notice = function() {
			Promotionsdetail.update_groupNotice($scope.group_id, $scope.input.notice, function(data) {
				if(data.rtnCode == 0) {
					//					$scope.get_groupinfo();
					$scope.data.group.group_notice = data.notice;
					GoDialog.toast('修改公告成功！');
				} else {
					GoDialog.toast(data.rtnMsg);
				}
			})
		};
		
		$scope.set_admin = function(user_id) {
			Promotionsdetail.set_main($scope.group_id, user_id, function(data) {
				if(data.rtnCode == 0) {
					$scope.get_groupinfo();
					GoDialog.toast('设置成功');
				} else {
					GoDialog.toast(data.rtnMsg);
				}
			})
		};
		$scope.set_black = function(user_id, user_name, is_black) {
			if($scope.whitle_list.length == 0)
				$scope.show_notice();
			else
				Promotionsdetail.set_black($scope.group_id, user_id, is_black, function(data) {
					if(data.rtnCode == 0) {
						$scope.get_groupinfo();
						if(is_black == 1) {
							var msg = '【' + user_name + '】' + '被群主拉黑(此为系统消息)';
						} else {
							var msg = '【' + user_name + '】' + '被群主解除拉黑(此为系统消息)';
						}
						$scope.send_message(msg);
					} else if(data.rtnCode == 10086) {
						GoDialog.toast(data.rtnMsg);
						GoPage.go_states("exchange_interaction");
					} else {
						GoDialog.toast(data.rtnMsg);
					}
				})
		};
		$scope.set_gag = function(user_id, user_name, is_gag) {
			Promotionsdetail.set_gag($scope.group_id, user_id, is_gag, function(data) {
				if(data.rtnCode == 0) {
					$scope.get_groupinfo();
					if(is_gag == 1) {
						var msg = '【' + user_name + '】' + '被群主禁言(此为系统消息)';
					} else {
						var msg = '【' + user_name + '】' + '被群主解除禁言(此为系统消息)';
					}
					$scope.send_message(msg);
				} else {
					GoDialog.toast(data.rtnMsg);
				}
			})
		}
		/*
		 * 群的黑白名单
		 */
		$scope.show_groupItem = function(member_id) {
			for(var i = 0; i < $scope.list.length; i++) {
				if(member_id == $scope.list[i].member_id)
					$scope.list[i].is_show = true;
				else
					$scope.list[i].is_show = false;
			}
		};
		$scope.doSearch = function() {
			Promotionsdetail.search_member($scope.group_id, $scope.input.key, function(data) {
				$scope.whitle_list = new Array();
				if(data.members != undefined) {
					for(var i = 0; i < data.members.length; i++) {
						if(data.members[i].is_black == 'false') {
							var j = $scope.whitle_list.length;
							$scope.whitle_list[j] = data.members[i];
						}
					}
					if($scope.is_admin == true) {
						$scope.list = data.members;
						document.getElementsByClassName('popup-title')[0].innerHTML = "群成员(" + data.members.length + "/" + $scope.data.group.max_gnum + ")";
					} else {
						$scope.list = $scope.whitle_list;
						document.getElementsByClassName('popup-title')[0].innerHTML = "群成员(" + $scope.whitle_list.length + "/" + $scope.data.group.max_gnum + ")";
					}
					$scope.search_msg = '';
				} else {
					$scope.search_msg = data.rtnMsg;
				}

			})
		};
		/*------------打开红包-----------*/
		$ionicModal.fromTemplateUrl("templates/modal/redBagCommonChat.html", {//没开：openRedbag.html； 开：openedRedbag.html
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modalRedbag = modal;
		});
		//关闭红包
		$scope.closeRedBagModal = function(){
			$scope.modalRedbag.hide();
		}
		/*
		 * 检查红包状态
		 */
		//打开一个modal对话框
		$scope.openModal = function(member_id, nickName, red_id, red_type, msg) {
			$scope.red_id = '';
			$scope.red_tip = "";//提示语，和祝福语是不一样的
			$scope.red_money = "";//红包金额
			$scope.nickName = nickName;
			$scope.red_memberId = member_id;
			$scope.red_message = msg;//祝福语，如：恭喜发财，大吉大利
//				$scope.red_type = red_type == 'fixed' ? '固定' : '随机';

			Promotionsdetail.check_bag(red_id, function(data) {
				if(data.rtnCode == 0) {//正常红包
					$scope.isShowRedBagOpen = false;
					$scope.modalRedbag.show();
					$scope.red_id = red_id;
				} else if(data.rtnCode == 1) {
					$scope.isShowRedBagOpen = true;
					$scope.red_tip = '来晚一步，红包已发完';
					$scope.modalRedbag.show();
				} else {
					$scope.isShowRedBagOpen = true;
					$scope.red_tip = '已存入预存款，可直接消费';//您已收过红包
					$scope.red_money = data.gotMoney;
					$scope.modalRedbag.show();
				}
			})
		};
		/*
		 * 打开红包
		 */
		$scope.open_red = function() {
			Promotionsdetail.open_red($scope.red_id, function(data) {
				if(data.rtnCode == 0) {
					$scope.isShowRedBagOpen = true;
					$scope.red_tip = '已存入预存款，可直接消费';
					$scope.red_money = data.gotMoney;
				} else {
					$scope.isShowRedBagOpen = true;
					$scope.red_tip = '来晚一步，红包已发完';
				}
			})
		};
		/*------------打开红包-----------*/
		
		$scope.send_message = function(data) {
			var accessType = 'get';
			var path = '/message/sendChat';
			var param = new Array();
			var message = "";//聊天内容：普通文字、图片、红包
			if(data){
				message = data;
			}else{
				message = $scope.textFromHtml($scope.input.message);
			}
			if(!message){
				GoDialog.toast("请先输入内容！");
				return;
			}	
			param['loginCode'] = $scope.login_code;
			param['message'] = message;
			param['groupId'] = $scope.group_code;
			param['frUserId'] = $scope.user_id;
			param['frUserName'] = $scope.user_name;
			param['toUserId'] = '';
			param['isAdvisory'] = 1;
			siginfo.sig = $scope.encode(accessType, path, param);
			Promotionsdetail.send_chat($scope.group_id, message, param, siginfo, function(data) {
				if(!data){
					GoDialog.toast("对不起，信息发送失败！");
					return;
				}
				if(data.rtnCode == 0) {
//					GoDialog.toast("发送成功");
					var input_message = new Array();
					var params = new Object();
					$scope.input.message = param['message'];
					params['content'] = emojione.toImage($scope.input.message);
					params['type'] = 'U';
					params['memberId'] = $scope.user_id;
					var date = new Date();
					params['sendTime'] = siginfo.ts.replace('T', ' ').substring(0, siginfo.ts.length - 4);
					input_message[0] = params;
					//					console.log($scope);
					$scope.show_message = $scope.show_message.concat(input_message);
					$scope.input.message = '';
					$scope.delegate.scrollBottom(true);
					//					console.log($scope.show_message);
				} else {
					GoDialog.toast(data.rtnMsg);
				}
			})
		}
		$scope.send_img = function(data) {
			var img_data = data;
			var accessType = 'get';
			var path = '/message/sendChat';
			var param = new Array();
			var message = $scope.textFromHtml($scope.input.message);
			param['loginCode'] = $scope.login_code;
			param['file'] = data;
			param['groupId'] = $scope.group_code;
			param['frUserId'] = $scope.user_id;
			param['frUserName'] = $scope.user_name;
			param['toUserId'] = '';
			param['isAdvisory'] = 1;
			siginfo.sig = $scope.encode(accessType, path, param);
			Promotionsdetail.send_img($scope.group_id, data, param, siginfo, function(data) {
				if(data.rtnCode == 0) {
//					GoDialog.toast("发送成功");
					var input_message = new Array();
					var params = new Object();
					params['url'] = img_data;
					params['type'] = 'P';
					params['memberId'] = $scope.user_id;
					var date = new Date();
					params['sendTime'] = siginfo.ts.replace('T', ' ').substring(0, siginfo.ts.length - 4);
					input_message[0] = params;
					$scope.show_message = $scope.show_message.concat(input_message);
					$scope.delegate.scrollBottom(true);
				} else {
					GoDialog.toast(data.rtnMsg);
				}
			})
		}
		//动态响应
		$scope.doShowFile = function() {
			document.getElementById("spicture-upfilebutton").click();
		}
		//图片上传
		$scope.onupload = function(val) {
			var fileList = val.files;
			for(var i = 0; i < val.files.length; i++) {
				var reader = new FileReader();
				reader.readAsDataURL(fileList[i]);
				var file = fileList[i];
				reader.onload = function(e) {
					//图片进行压缩处理
					GoPicture.compress(file,e.target.result, 50, function(base64) {
						$scope.$apply(function() {
							//							console.log(base64);
							if(base64) {
								$scope.send_img(base64);
								val.value = "";
							}
						});
					});
				}
			}
		};
		
		
		//查看大图
		$scope.showBigImg = function(imgUrl) {
			GoDialog.showBigImg(imgUrl);
		}
		
		/*********************************聊天群******************************/
		$scope.switchGroup = function(index) {
			if(index == 0) {
				$scope.selectIndex = 0;
			} else {
				$scope.selectIndex = 1;
			}
			if($scope.group_id != $scope.group[index].group_id) {
				$scope.other_group_id = $scope.group_id;
				$scope.other_group_code = $scope.group_code;
				$scope.group_id = $scope.group[index].group_id;
				$scope.group_code = $scope.group[index].group_code;
				var msg = $scope.show_message;
				$scope.show_message = $scope.other_message;
				$scope.other_message = msg;
				var histroyId = $scope.histroyMsg_id;
				$scope.otherHistoryMsg_id = histroyId;
				$scope.histroyMsg_id = $scope.otherHistoryMsg_id;
				var firstHistory = $scope.is_firstHistroy;
				$scope.is_firstHistroy = $scope.is_otherFirstHistroy;
				$scope.is_otherFirstHistroy = firstHistory;
				$scope.input.key = null;
				$scope.get_groupinfo();
			}
		}
		$scope.init_data = function() {
			$scope.input = new Object();
			$scope.selectIndex = 0;
			$scope.input.message = '';
			$scope.isLoad = false; //可以加载
			$scope.act_id = $stateParams.act_id;
			$scope.as_id = $stateParams.as_id;
			$scope.goods_list = new Object();
			$scope.datas = new Object();
			$scope.group_style = {
				"background": "#E01223",
				"color": "#FFFFFF"
			};
			$scope.group_style1 = {
				"background": "#FFCC66",
				"color": "#FFFFFF"
			};
			//生成对象
			$scope.player = null;
			$scope.playering = 0;
			$scope.playerNum = 0;
			$scope.scope = new Object();
			emojione.imagePathPNG = 'img/emojione/2.2.7/assets/png/';
			$scope.emoji_map = new Object();
			$scope.init_emoji();
			$scope.livedata();
			//需要重复初始化
		}
		//初始化聊天
		$scope.init_chat = function() {
			$scope.show_message = new Array();
			$scope.isLoad = false;
			$scope.is_firstHistroy = true;
			$scope.is_otherFirstHistroy = true;
			$scope.biaoClass = "";
			$scope.whitle_list = new Array();
			$scope.input.key = null;
			$scope.msg_id = 0;
			$scope.histroyMsg_id = '';
			$scope.otherHistoryMsg_id = '';
			$scope.black_list = new Array();
			$scope.member_logo = new Array();
			$scope.chats = new Array();
			$scope.delegate = $ionicScrollDelegate.$getByHandle('main-content');
			$scope.get_groupinfo();
			$scope.get_message();
		}
		
		/***************群公告**************/
		$ionicModal.fromTemplateUrl("templates/modal/groupNotice.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_notice = modal;
		});
		//打开
		$scope.openModal_notice = function() {
			if(!$scope.data||!$scope.data.group||!$scope.data.group.group_notice) {
				GoDialog.alert("提示","暂时没有群公告哦！");
				return;
			}
			$scope.groupNotice = $scope.data.group.group_notice;
			$scope.modal_notice.show();
		}
		//隐藏
		$scope.closeModal_notice = function() {
			$scope.modal_notice.hide();
		}
		/***************群公告**************/

		/***************群成员**************/
		$ionicModal.fromTemplateUrl("templates/modal/groupMember.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_member = modal;
		});
		//打开
		$scope.openModal_member = function() {
//			console.log($scope.list)
			if(!$scope.list) {
				GoDialog.alert("提示","暂时没有群成员哦！");
				return;
			}
			$scope.modal_member.show();
		}
		//隐藏
		$scope.closeModal_member = function() {
			$scope.modal_member.hide();
		}
		/***************群成员**************/
		
		/***************发红包**************/
		//初始化红包参数
		function initRedBag(){
			$scope.rule = 'fixed';//默认平分。random：随机
			$scope.input.count = '';
			$scope.input.money = '';
			$scope.input.memo = '';
		}
		//选择规则
		$scope.rule_choose = function(rule) {
			$scope.rule = rule;
		};
		$ionicModal.fromTemplateUrl("templates/modal/chatGiveRedBag.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_red = modal;
		});
		//打开
		$scope.openModal_red = function() {
			initRedBag();//初始化红包参数
			$scope.modal_red.show();
		}
		//隐藏
		$scope.closeModal_red = function() {
			$scope.modal_red.hide();
		}
		
		//输入密码框
		$ionicModal.fromTemplateUrl("templates/modal/confirm_pay.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_confirm = modal;
		});
		//预存款支付
		$scope.openModal_confirm = function() {
			if(!$scope.input.money) {
				GoDialog.toast("请输入红包金额");
				return;
			} 
			if(!$scope.input.count) {
				GoDialog.toast("请输入红包个数");
				return;
			}
			if($scope.input.count>$scope.max_redNum){
				GoDialog.toast("最多只能发"+$scope.max_redNum+"人");
				return;
			}
//			if($scope.input.money>$scope.advance){
//				GoDialog.toast("红包金额不能大于账号余额");
//				return;
//			}
			$scope.idRedBag = true;//控制文字
			//每次打开modal，必须初始化以下2个变量
			$scope.input.password = "";
			$scope.showPotArr = new Array();
			$scope.modal_confirm.show();//满足输入条件，才弹窗
			$scope.getInputFocus();
		}
		$scope.closeModal_confirm = function(index) {
			$scope.modal_confirm.hide();
		}
		//获取焦点
		$scope.getInputFocus = function($event){
			if($event){
				$event.stopPropagation();//阻止事件冒泡
			}
			document.getElementById("inputPass").focus();
		}
		
		//输入密码监听
		$scope.$watch('input.password', function(newValue, oldValue) {
			$scope.showPotArr = new Array();//控制密码点的显示
			if(!newValue){
				return
			}
			if(newValue.length>6) {//6为密码
				newValue = newValue.substring(0, 6);
			}
			$scope.input.password = newValue;
			for (var i=0;i<$scope.input.password.length;i++) {
				$scope.showPotArr.push(i+1);
			}
			if($scope.input.password.length==6){//密码够6位，自动提交
				document.getElementById("inputPass").blur();//防止继续输入
				submitRedBag();
			}
		})
		
		//提交红包
		function submitRedBag(){
			if(!$scope.input.memo){//如果为空，则默认“恭喜发财，大吉大利”。
				$scope.input.memo = "恭喜发财，大吉大利";
			}
			Promotionsdetail.packets_grant($scope.group_id, $scope.input.money, $scope.input.count, $scope.rule, $scope.input.memo, $scope.input.password,function(data) {
				if(!data.success){
					GoDialog.alert("提示",data.msg,function(){
						$scope.closeModal_confirm();
					});
					return;
				}
				data = data.result;
				if(data.rtnCode == 0) {
					//GoDialog.toast("红包发送成功");
					$scope.closeModal_confirm();
					$scope.closeModal_red();
					var accessType = 'get';
					var path = '/message/sendChat';
					var param = new Array();
					var message = data.rtnMsg;
					param['loginCode'] = $scope.login_code;
					param['message'] = data.rtnMsg;
					param['groupId'] = $scope.group_code;
					param['frUserId'] = $scope.user_id;
					param['frUserName'] = $scope.user_name;
					param['toUserId'] = '';
					param['isAdvisory'] = 1;
					siginfo.sig = $scope.encode(accessType, path, param);
					Promotionsdetail.send_msg($scope.chat_url, data.rtnMsg, param, siginfo, $scope.group_id, function(data) {
						if(data.rtnCode == 0) {
							var input_message = new Array();
							var params = new Object();
							params['content'] = message;
							params['hongbao'] = message.split(':');
							params['type'] = 'U';
							params['nickName'] = $scope.user_name;
							params['memberId'] = $scope.user_id;
							var date = new Date();
							params['sendTime'] = siginfo.ts.replace('T', ' ').substring(0, siginfo.ts.length - 4);
							input_message[0] = params;
							$scope.show_message = $scope.show_message.concat(input_message);
							$scope.delegate.scrollBottom(true);
						} else {
							GoDialog.toast(data.rtnMsg);
						}
					})
				} else {
					GoDialog.alert("提示",data.rtnMsg,function(){
						$scope.closeModal_confirm();
						$scope.closeModal_red();
					});
				}
			})
		}
		/***************发红包**************/
		
		
		
	}

	controller.$inject = ['$scope', 'Promotionsdetail', '$stateParams', '$window', '$timeout', '$ionicSlideBoxDelegate', 'GoPage', 'GoDialog',
		'$ionicModal', '$ionicPopup', 'Auth', 'ChatInfo', 'GoPicture', '$ionicPlatform', 'GoChat', '$ionicScrollDelegate'
	];

	return app.registerController("promotionspicturectrl", controller);
});